﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Linq;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AzureContrib.WindowsAzure.IntegrationTests
{
	[TestClass]
	public class PublishSettingsFileTests
	{
		[TestMethod]
		public void List_Deployments()
		{
			string file = "<fileName>";

			var profile = XDocument.Load(file);

			var requestUriString = string.Format("https://management.core.windows.net/{0}/services/hostedservices", profile.Descendants("Subscription").First().Attribute("Id").Value);
			var requestUri = new Uri(requestUriString);
			var request = (HttpWebRequest)WebRequest.Create(requestUri);

			request.Headers["x-ms-version"] = "2011-10-01";

			var managementCertificateValue = profile.Descendants("PublishProfile").Single().Attribute("ManagementCertificate").Value;
			var rawData = Convert.FromBase64String(managementCertificateValue);
			var X509Certificate2 = new X509Certificate2(rawData);

			request.ClientCertificates.Add(X509Certificate2);

			XNamespace xmlns = "http://schemas.microsoft.com/windowsazure";

			var response = request.GetResponse();
			var responseDoc = XDocument.Load(response.GetResponseStream());
			var services = responseDoc.Descendants(xmlns + "ServiceName").Select(n => n.Value).ToArray();

			var message = string.Join("\n", services);
			Debug.WriteLine(message);
		}
	}
}